package com.hxalex.simulationhandle.ui.permission.manger;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;

import com.hxalex.simulationhandle.accessbilityService.HandleService;
import com.hxalex.simulationhandle.accessbilityService.receiver.wifi.service.WifiInfoService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by hx_Alex on 2018/5/24.
 */

public class PermissionManger {
    public static final String TAG = "PermissionManger";
    public static int OVERLAY_PERMISSION_REQ_CODE = 1234;
    public static final int ISHAVE_ACCESSBILITY_SERVICE = 0x001;
    public static final int ISHAVE_READ_EXTERNAL_STORAGE = 0x002;
    public static final int ISHAVE_OPEN_WIFI = 0x003;
    public static final int ISHAVE_SYS_dl = 0x004;
    public String[] permissionList = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE};
    public HashMap<Integer, Boolean> havaPermissionMap = new HashMap<>();
    private static Activity context;
    public boolean isHaveAllPermission = false;
    private static PermissionManger manger;
    private List<onPermissionListener> onPermissionListeners;


    private PermissionManger(Activity context) {
        PermissionManger.context = context;
        onPermissionListeners = new ArrayList<>();
        checkAllPermission();
    }

    public static PermissionManger getManger(Activity context) {
        PermissionManger.context = context;
        if (manger == null) manger = new PermissionManger(context);
        return manger;
    }

    public void setOnPermissionListener(PermissionManger.onPermissionListener onPermissionListener) {
        if (onPermissionListener != null) onPermissionListeners.add(onPermissionListener);
    }

    public void removeOnPermissionListener(PermissionManger.onPermissionListener onPermissionListener) {
        int i = onPermissionListeners.indexOf(onPermissionListener);
        if (i != -1) onPermissionListeners.remove(i);
    }

    public HashMap<Integer, Boolean> getHavaPermissionMap() {
        return havaPermissionMap;
    }

    public boolean checkIsHavePermission(String permission) {
        int hasReadExternalStoragePermission = ContextCompat.checkSelfPermission(context, permission);

        if (hasReadExternalStoragePermission == PackageManager.PERMISSION_DENIED) {
            return false;
        }
        return true;
    }

    private boolean isWifiOpened() {
        WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        return wifiManager.isWifiEnabled();
    }

    public void toggleWiFi(Context context, boolean enabled) {
        WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        wifiManager.setWifiEnabled(enabled);
        Intent i=new Intent(context, WifiInfoService.class);
        i.setAction(WifiInfoService.WIFI_STATE);
        context.startService(i);
    }

    public void startApplyPermission(Context context,String permission) {
        if (context instanceof Activity) {
            ActivityCompat.requestPermissions((Activity) context, new String[]{permission}, 1);
        } else {
            Intent intent = IntentgetAppDetailSettingIntent(context);
            context.startActivity(intent);
        }
    }

    public void onRequestPermissionsResult(String permission, int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {

            if (permissions[0].equals(permission) && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                checkAllPermission();
            } else {
                //若用户不同意授权，直接暴力退出应用。
                // 当然，这里也可以有比较温柔的操作。
                if (!ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, permissions[0])) {
                    Intent intent = IntentgetAppDetailSettingIntent(context);
                    context.startActivity(intent);
                }

            }
        }else if(requestCode==2)
        {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (Settings.canDrawOverlays(context)) {
                    checkAllPermission();
                }
            }
        }
    }

    private Intent IntentgetAppDetailSettingIntent(Context context) {
        Intent localIntent = new Intent();
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            localIntent.setData(Uri.fromParts("package", context.getPackageName(), null));
        } else if (Build.VERSION.SDK_INT <= 8) {
            localIntent.setAction(Intent.ACTION_VIEW);
            localIntent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
            localIntent.putExtra("com.android.settings.ApplicationPkgName", context.getPackageName());
        }
        return localIntent;
    }
    
    
    private boolean checkIsSystemAlertDialogPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.canDrawOverlays(context)) {
                return false;
            }
        }
        return true;
    }
    
    public void requstOpenSystemAlertDialogPermission()
    {
        Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + context.getPackageName()));
        context.startActivityForResult(intent, OVERLAY_PERMISSION_REQ_CODE);
    }


    public Map<Integer, Boolean> checkAllPermission() {

        boolean accessibilitySettingsOn = isAccessibilitySettingsOn(context);
        boolean haveReadStorage = checkIsHavePermission(permissionList[0]);
        boolean isHaveOpenWifo=isWifiOpened();
        boolean IsSystemAlertDialogPermission=checkIsSystemAlertDialogPermission();
        havaPermissionMap.put(ISHAVE_ACCESSBILITY_SERVICE, accessibilitySettingsOn);
        havaPermissionMap.put(ISHAVE_READ_EXTERNAL_STORAGE, haveReadStorage);
        havaPermissionMap.put(ISHAVE_OPEN_WIFI, isHaveOpenWifo);
        havaPermissionMap.put(ISHAVE_SYS_dl, IsSystemAlertDialogPermission);
        if (accessibilitySettingsOn && haveReadStorage && isHaveOpenWifo && IsSystemAlertDialogPermission) {
            isHaveAllPermission = true;
        } else {
            isHaveAllPermission = false;
        }


        for (onPermissionListener l : onPermissionListeners) {
            l.onPermissionCheck();
        }
        return havaPermissionMap;
    }


    /**
     * 检测辅助功能是否开启
     *
     * @param mContext
     * @return boolean
     */
    private boolean isAccessibilitySettingsOn(Context mContext) {
        int accessibilityEnabled = 0;
        // TestService为对应的服务  
        final String service = context.getPackageName() + "/" + HandleService.class.getCanonicalName();
        Log.i(TAG, "service:" + service);
        // com.z.buildingaccessibilityservices/android.accessibilityservice.AccessibilityService  
        try {
            accessibilityEnabled = Settings.Secure.getInt(mContext.getApplicationContext().getContentResolver(),
                    android.provider.Settings.Secure.ACCESSIBILITY_ENABLED);
            Log.v(TAG, "accessibilityEnabled = " + accessibilityEnabled);
        } catch (Settings.SettingNotFoundException e) {
            Log.e(TAG, "Error finding setting, default accessibility to not found: " + e.getMessage());
        }
        TextUtils.SimpleStringSplitter mStringColonSplitter = new TextUtils.SimpleStringSplitter(':');

        if (accessibilityEnabled == 1) {
            Log.v(TAG, "***ACCESSIBILITY IS ENABLED*** -----------------");
            String settingValue = Settings.Secure.getString(mContext.getApplicationContext().getContentResolver(),
                    Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
            // com.z.buildingaccessibilityservices/com.z.buildingaccessibilityservices.TestService  
            if (settingValue != null) {
                mStringColonSplitter.setString(settingValue);
                while (mStringColonSplitter.hasNext()) {
                    String accessibilityService = mStringColonSplitter.next();

                    Log.v(TAG, "-------------- > accessibilityService :: " + accessibilityService + " " + service);
                    if (accessibilityService.equalsIgnoreCase(service)) {
                        Log.v(TAG, "We've found the correct setting - accessibility is switched on!");
                        return true;
                    }
                }
            }
        } else {
            Log.v(TAG, "***ACCESSIBILITY IS DISABLED***");
        }
        return false;
    }


    public void jumpSetOpenAccessibilitySetting() {
        if (!isAccessibilitySettingsOn(context)) {
            Intent intent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
            context.startActivity(intent);
        }
    }
    
    public interface onPermissionListener {
        void onPermissionCheck();
    }



}
